package com.book.util;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.book.model.vo.IsbnBookDetailVO;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: 125715
 * @Package: com.book.util
 * @Date: 2025/4/5 18:16
 * @Description: 图书工具类
 */

@Component
public class BookUtil {

    @Value("${tushu.appKey}")
    private String appKey;

    @Value("${tushu.requestUrl}")
    private String requestUrl;

    public IsbnBookDetailVO getBookMessageByIsbn(String isbn) throws IOException {
        // 构建请求 URL
        String urlString = requestUrl + "?isbn=" + isbn + "&appKey=" + appKey;

        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpGet request = new HttpGet(urlString);

            // 发送请求并获取响应
            return client.execute(request, response -> {
                if (response.getCode() == 200) {
                    String responseBody = EntityUtils.toString(response.getEntity());
                    // 解析响应数据
                    return parseResponse(responseBody);
                } else {
                    throw new IOException("请求失败，响应码：" + response.getCode());
                }
            });
        }
    }

    private IsbnBookDetailVO parseResponse(String response) {
        // 使用 Gson 解析 JSON 数据
        JsonObject jsonObject = JsonParser.parseString(response).getAsJsonObject();
        JsonObject data = jsonObject.getAsJsonObject("data");
        // 创建 IsbnBookDetailVO 对象
        IsbnBookDetailVO bookDetail = new IsbnBookDetailVO();
        // 逐个设置字段值
        bookDetail.setIsbn(data.get("isbn").getAsString());
        bookDetail.setName(data.get("bookName").getAsString());
        bookDetail.setAuthor(data.get("author").getAsString());
//        bookDetail.setIntroduction(data.get("bookDesc").getAsString());
//        bookDetail.setPicture(data.get("img").getAsString());
        bookDetail.setPrice(new BigDecimal(data.get("price").getAsLong() / 100.0)); // 假设 price 是以分为单位
        bookDetail.setOriginPrice(new BigDecimal(data.get("price").getAsLong() / 100.0)); // 假设 price 是以分为单位
        bookDetail.setPublisher(data.get("press").getAsString());
        bookDetail.setPublishLocation(data.get("pressPlace").getAsString());
        bookDetail.setPublishDate(parseDate(data.get("pressDate").getAsString())); // 解析日期
        bookDetail.setBindingType(data.get("binding").getAsString());
        bookDetail.setBookSize(data.get("format").getAsString());
        bookDetail.setPageSize(parsePageSize(data.get("pages").getAsString())); // 解析页数
        bookDetail.setSummary(data.get("bookDesc").getAsString());
        bookDetail.setPrintDate(parseDate(data.get("pressDate").getAsString())); // 解析日期
        String edition = data.get("edition").getAsString();
        bookDetail.setEdition(StringUtils.isNotBlank(edition)?"第"+edition+"版":"暂无");
        return bookDetail;
    }
    // 解析日期字符串为 Date 对象
    private Date parseDate(String dateStr) {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
            return format.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 解析页数字符串为 Long 类型
    private Long parsePageSize(String pages) {
        return Long.parseLong(pages.replace("页", ""));
    }
}

